<template>
  <div class="auth-management">
    <div :gutter="20" class="content-row">
      <div>
        <div class="left-panel">
          <div class="panel-header">
            <span>权限组</span>
          </div>
          <div class="new-add-button add-auth-button" @click="handleAddAuth">
            <img src="@/assets/images/svg/plus.png" class="plus" alt="" />新增
          </div>

          <!-- 左侧权限树 -->
          <el-tree ref="permissionTree" class="permission-tree" style="max-width: 600px" :data="treeData"
            :props="defaultProps" node-key="accessGroupId" :expand-on-click-node="false" :highlight-current="true"
            @node-click="handleNodeClick" :default-expand-all="true" empty-text="暂无数据" />

        </div>

      </div>

      <!-- 不是新增的时候就显示编辑权限状态 -->
      <div v-if="!isAddMode" class="right-panel">
        <!-- 展示权限详情展示组件 -->
        <auth-detail :auth-data="currentAuthData" @edit="handleEdit" @delete="handleDelete" />
      </div>


      <!-- 权限新增展示的右侧内容 -->
      <div v-else class="right-panel">
        <div class="detail-header">
          <span>{{ isEditMode ? '编辑权限组' : '新增权限组' }}</span>
        </div>

        <!-- 权限新增显示的组件 -->
        <add-auth-form :currentAuthData="currentAuthData" ref="addAuthFormRef" @submit="confirmAddAuth"
          @cancel="cancelAddAuth" />

      </div>


    </div>

    <!-- 添加权限编辑弹窗组件 -->
    <permission-edit-dialog ref="permissionDialogRef" :initial-permissions="currentAuth.permissions"
      @update:permissions="updatePermissions" />

  </div>
</template>

<script setup lang="ts">
import { getAccessRight, getListByCreate, deleteAccessRight, getAdminListGroup } from "@/apis/accessGroup";


import { ElMessageBox } from "element-plus";
import { computed, nextTick, onMounted, reactive, ref, h } from "vue";


import AddAuthForm from "./components/AddAuthForm.vue";
import AuthDetail from "./components/AuthDetail.vue";
import PermissionEditDialog from "./components/PermissionEditDialog.vue"; //引入PermissionEditDialog组件



const { t } = useI18n()



const permissionTree = ref(null);
const defaultProps = {
  children: "children",
  label: "groupName",
};





import { useTreeBuilder } from "@/hooks/useTreeBuilder";
import { errorTips, successTips } from "@/utils/utils";
import { useI18n } from "vue-i18n";
const { treeData, buildTree } = useTreeBuilder();



//发送请求获取权限参数并且利用方法重构成树形结构渲染菜单权限树到左侧展示
const getForSelect = () => {
  return getListByCreate().then((res) => {
    if (!res.data || res.data.length === 0) {
      return;
    }
    buildTree(res.data);
    return treeData.value;
  })
    .catch((err) => { });
};



//定义节点中选中的权限参数
const currentAuth = reactive({
  id: "",
  name: "",
  accessGroupId: "",
  permissions: [],
  parentGroupId: "", // 添加parentGroupId属性
  hasChildren: false, // 标记当前节点是否有子节点
});

//添加模式控制的变量
const isAddMode = ref(false);
//初始化管理权限数组
const managePermissions = ref([]);
//初始化查看权限数组
const viewPermissions = ref([]);
//管理用户列表
const adminUsers = ref([]);


//左侧权限树 点击节点触发选择权限
const handleNodeClick = (data: any) => {
  // 更新当前选中的权限组信息
  currentAuth.accessGroupId = data.accessGroupId;
  currentAuth.id = data.accessGroupId;
  currentAuth.name = data.groupName;
  currentAuth.parentGroupId = data.parentGroupId; //更新parentGroupId
  // 判断当前节点是否有子节点
  currentAuth.hasChildren = data.children && data.children.length > 0;

  isAddMode.value = false;

  //处理节点点击事件，获取节点对应的权限信息
  let queryParams = {
    accessGroupId: data.accessGroupId,
    parentId: data.parentGroupId,
  };

  // 如果是超级管理员节点，修改请求参数
  if (data.accessGroupId == 1 && data.parentGroupId == 0) {
    queryParams = {
      accessGroupId: 0,
      parentId: 1,
    };
  }


  //获取当前节点对应的权限参数
  getAccessRight(queryParams)
    .then((res) => {

      //将原始权限数据传递给权限编辑弹窗组件
      if (permissionDialogRef.value) {
        //定义一个原始的权限参数对象，把父级以及子级对应的权限参数传递到编辑权限弹窗的组件
        const originalRightData = {
          parentRoleRightViewGroupList: res.data.parentRoleRightViewGroupList || [],
          roleRightViewGroupList: res.data.roleRightViewGroupList || [],
        };
        permissionDialogRef.value.setOriginalRightData(originalRightData);
      }

      //没有权限参数返回的时候则清空数据
      if (
        !res.data ||
        !res.data.roleRightViewGroupList ||
        res.data.roleRightViewGroupList.length === 0
      ) {
        // 如果没有权限数据，清空权限列表
        managePermissions.value = [];
        viewPermissions.value = [];
        return;
      }

      //重构权限参数对应的权限数据，处理好的权限参数传入到定义好的currentAuth里面
      const permissions = res.data.roleRightViewGroupList

        .map((item) => {
          return {
            accessRightDefaultId: Number(item.accessRightDefaultId),
            groupName: item.groupName,
            // accessType: 1代表管理权限，2代表查看权限，0代表无权限
            view: item.accessType === 2,
            manage: item.accessType === 1,
          };
        })
        .filter((item) => item.view || item.manage); // 只保留有权限的项

      // 更新权限数据
      currentAuth.permissions = permissions;

      // 提取管理权限和查看权限
      const managePerm = permissions.filter((p) => p.manage).map((p) => p.groupName);

      const viewPerm = permissions
        .filter((p) => p.view && !p.manage)
        .map((p) => p.groupName);

      //渲染的管理权限数组
      managePermissions.value = managePerm;
      //渲染的查看权限数组
      viewPermissions.value = viewPerm;
    });


  getAdminListGroup
    ({ accessGroupId: data?.accessGroupId || 1 })
    .then((res) => {
      if (!res.data || res.data.length === 0) {
        // 如果没有用户数据，清空用户列表
        adminUsers.value = [];
        return;
      }
      // 将API返回的用户数据转换为组件所需格式
      adminUsers.value = res.data.map((item: any) => ({
        id: item.userId,
        name: item.userName,
        type: item.type || "admin",
      }));
    })
    .catch((error) => {
      adminUsers.value = [];
    });
};



onMounted(async () => {
  // 等待树数据加载完成
  await getForSelect();
  //直接使用特定参数调用handleNodeClick
  handleNodeClick({
    accessGroupId: 0,
    groupName: "超级管理组",
    parentGroupId: 1,
  });
});




//新增权限组相关状态
const isEditMode = ref(false);
const addAuthFormRef = ref();
//定义一个传入编辑以及新增组件的计算属性
const currentAuthData = computed(() => {
  //定义一个数组用于提取管理权限id 以及 查看权限的id
  const accessRightDefaultIds = {
    manage: [],
    view: [],
  };

  //如果有权限数据，提取ID
  if (currentAuth.permissions && currentAuth.permissions.length > 0) {
    //提取管理权限的ID
    accessRightDefaultIds.manage = currentAuth.permissions
      .filter((p) => p.manage)
      .map((p) => p.accessRightDefaultId);

    //提取查看权限的ID
    accessRightDefaultIds.view = currentAuth.permissions
      .filter((p) => p.view && !p.manage)
      .map((p) => p.accessRightDefaultId);
  }

  return {
    id: currentAuth.id,
    accessGroupId: currentAuth.accessGroupId,
    name: currentAuth.name,
    users: adminUsers.value,
    managePermissions: managePermissions.value,
    viewPermissions: viewPermissions.value,
    accessRightDefaultIds: accessRightDefaultIds, // 添加权限ID信息
    permissions: currentAuth.permissions, // 传递完整的权限数据
    parentGroup: currentAuth.parentGroupId, // 使用parentGroupId作为父组ID，确保编辑时能正确显示
    parentGroupId: currentAuth.parentGroupId, // 同时传递parentGroupId，确保API请求时使用正确的值
    hasChildren: currentAuth.hasChildren, // 标记当前节点是否有子节点
  };

});



//权限树上方新增权限事件
const handleAddAuth = () => {
  isAddMode.value = true;
  isEditMode.value = false;

  //重置之前写入的新增权限数据
  currentAuth.id = "";
  currentAuth.name = "";
  currentAuth.permissions = [];
  currentAuth.parentGroupId = ""; // 重置parentGroupId
  currentAuth.hasChildren = false; // 重置hasChildren


  // 设置为非编辑模式并传递空数据
  if (addAuthFormRef.value) {
    addAuthFormRef.value.setEditMode(false);
    // 传递空数据以重置表单
    addAuthFormRef.value.setFormData({
      id: "",
      name: "",
      users: [],
      managePermissions: [],
      viewPermissions: [],
      accessRightDefaultIds: {
        manage: [],
        view: [],
      },
      permissions: [],
    });
  }
};



//确认添加权限组
const confirmAddAuth = (formData: any, queryAccessGroupIdParentId: any) => {
  // 检查是否需要强制刷新
  const needRefresh = formData && formData.refresh === true;
  if (needRefresh) {
    getForSelect()
    // handleNodeClick(queryAccessGroupIdParentId);
    const superAdminNode = {
      accessGroupId: 0,
      groupName: "超级管理组",
      parentGroupId: 1,
    };

    handleNodeClick(superAdminNode);

    // 使用nextTick确保DOM更新后再设置当前节点
    nextTick(() => {
      if (permissionTree.value) {
        // 设置树组件的当前节点为超级管理组
        permissionTree.value.setCurrentKey(0); // 使用accessGroupId作为key
      }
    });

    successTips('操作成功')

    return;
  }


  // 处理权限数据
  const managementPerms = [];
  const viewPerms = [];

  // 遍历权限数据
  if (formData.permissions) {
    Object.keys(formData.permissions).forEach((key) => {
      const permission = formData.permissions[key];
      // 有管理权限的放入管理权限数组
      if (permission.manage) {
        const permName = getPermissionName(key);
        if (permName) managementPerms.push(permName);
      }
      // 只有查看权限的放入查看权限数组
      else if (permission.view) {
        const permName = getPermissionName(key);
        if (permName) viewPerms.push(permName);
      }
    });
  }

  managePermissions.value = managementPerms;
  viewPermissions.value = viewPerms;
  isAddMode.value = false;

  // 重置编辑模式
  if (addAuthFormRef.value) {
    addAuthFormRef.value.setEditMode(false);
  }
  getForSelect();
  nextTick(() => {
    if (permissionTree.value) {
      permissionTree.value.setCurrentKey(queryAccessGroupIdParentId.accessGroupId);
    }
  });
};



//获取权限名称
const getPermissionName = (key: string) => {
  const permissionMap: Record<string, string> = {};
  return permissionMap[key] || key;
};



//编辑权限组
const handleEdit = (id: string) => {
  isAddMode.value = true;
  isEditMode.value = true;
  //直接更新currentAuth对象，而不是尝试修改计算属性
  //确保权限数据被正确复制
  if (currentAuth.permissions) {
    //不需要额外操作，因为currentAuth已经包含了必要的数据
  }
  //等待DOM更新后，设置表单为编辑模式
  nextTick(() => {
    if (addAuthFormRef.value) {
      addAuthFormRef.value.setEditMode(true);
      // 使用currentAuthData计算属性作为表单数据
      addAuthFormRef.value.setFormData(currentAuthData.value);
    }
  });
};



//添加权限组件重置模式状态功能事件
const cancelAddAuth = () => {
  //重置模式状态
  isAddMode.value = false;
};


//删除权限组
const handleDelete = (id: any) => {
  ElMessageBox.confirm("删除后数据无法恢复，确认删除吗?", '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteAccessRight({ accessGroupId: id }).then((res) => {
        if (res.code === 1) {
          successTips('删除成功')
          // 删除成功后，直接使用特定参数加载超级管理员权限数据
          handleNodeClick({
            accessGroupId: 0,
            groupName: "超级管理组",
            parentGroupId: 1,
          });

          //刷新权限组列表
          getForSelect();
        }
      })
        .catch((err) => {
          errorTips('删除失败')
        });
    })
    .catch(() => { });
};


//权限编辑弹窗相关
const permissionDialogRef = ref(); //引用PermissionEditDialog组件
const updatePermissions = (permissions: any) => {
  // 更新当前权限数据
  currentAuth.permissions = permissions;
};




</script>
<style scoped lang="scss">
.auth-management {
  height: 100%;

  .content-row {
    height: 100%;
    display: flex;

    .left-panel {
      background-color: #fff;
      height: 100%;
      padding: 20px 20px 0 20px;
      width: 240px;
      border-right: 1px solid #e2e2e2;
      overflow: auto;

      .permission-tree {
        padding: 10px;
        // height: calc(100% - 100px);
        min-height: 200px;
        overflow: auto;
      }

      .panel-header {
        font-size: 16px;
        font-weight: 800;
        color: #020131;
        height: 50px;
        display: flex;
        align-items: center;
      }

      .add-auth-button {
        width: 100%;
        margin-bottom: 10px;
        background: #2258F6;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 32px;
        color: #fff;
        cursor: pointer;

        .plus {
          width: 16px;
          height: 16px;
          margin-right: 10px;
          object-fit: cover;
        }
      }
    }

    .right-panel {
      width: 100%;
      overflow-y: auto;
      flex: 1;
      background: #ffffff;
      margin-left: 2px;
      padding: 20px 20px 0 20px;

      .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 800;
        height: 50px;
        padding: 14px 12px;
        font-size: 16px;
        color: #020131;
        background-color: #f4f4f9;
      }
    }
  }
}

.el-tree {
  :deep(.el-tree-node__content) {
    display: flex;
    align-items: center;
    gap: 3px;
    font-weight: 800;
    font-size: 14px;
    color: #9f9f9f;
    gap: 5px;
    margin-bottom: 5px;
  }

  :deep(.el-tree-node__children) {
    .el-tree-node__content {
      font-size: 14px;
      color: #02011b;
    }
  }
}
</style>
